<template>
  <view>
    <nav-bar :is-back-icon="false" :page-title="lang.page_name"/>

    <view class="padding-40">
      <view :class="['card shadow padding-28-40', locale]">
        <view>

          <view class="text-34 margin-bottom-40">
            {{ `${lang.print_tag[printParams.dmPaperSize]} (${lang.print_tag[printParams.dmOrientation]})` }}
          </view>
          <!-- بىرىنچى قۇر مەلۇماتلار -->
          <view class="flex-between margin-bottom-20">
            <!-- بېسىش يۆنىلىشى -->
            <view class="column-center gap-20">
              <text class="text-32 color-grey">{{ lang.print_state }}</text>
              <text class="text-34">{{ printParams.dmOrientation === 1 ? lang.single : lang.double }}</text>
            </view>

            <!-- رەڭلىك/قارا -->
            <view class="column-center gap-20">
              <text class="text-32 color-grey">{{ lang.print_color }}</text>
              <text class="text-34">{{ printParams.dmColor === 1 ? lang.not_colored : lang.colored }}</text>
            </view>

            <!-- 单价 -->
            <view class="column-center gap-20">
              <text class="text-32 color-grey">{{ lang.unit_price }}</text>
              <text class="text-34">{{ myReplace(lang.price_value, '{index}', getUnitPrice) }}</text>
            </view>

            <!-- 已选择 -->
            <view class="column-center gap-20">
              <text class="text-32 color-grey">{{ otherLang.selected }}</text>
              <text class="text-34">{{ myReplace(lang.selected_value, '{index}', selectedData.length) }}</text>
            </view>
          </view>

          <!-- 打印次数 -->
          <view class="flex-between copies-row">
            <text class="text-32 color-grey">{{ lang.copies_printed }}</text>
            <text class="text-34">{{ `${printParams.dmCopies} ${otherLang.copies}` }}</text>
          </view>

          <!-- جەمئىي باھاسى -->
          <view class="flex-between total-row">
            <text class="text-32 color-grey">{{ otherLang.total_price }}</text>
            <view class="flex-center gap-10">
              <image style="width: 44rpx; height: 44rpx;filter: sepia(100%) saturate(10000%) hue-rotate(0deg);"
                     src="/static/globalIcon/rmb.svg"/>
              <view style="font-size: 44rpx;font-weight: bold;color: #ff0000">{{ getPrice(totalPrice) }}</view>
            </view>
            <!--              <u-text size="22" color="red" bold :text="totalPrice" mode="price"/>-->
          </view>
        </view>
      </view>

      <!-- 选择tabs-->
      <Tabs :list="lang.tabs" @click="handleTabClick" :select="selectedTab"/>

      <view style="margin-top: 30rpx">
        <view class="flex-row wrap" style="gap: 26rpx">
          <view v-for="(item, index) in imageList"
                :style="[{width:printParams.dmOrientation === 2 ? '100%' : '48%'}]">
            <image :class="['margin-bottom-20 content-paper',{'selected':item.selected}]" :src="item.image"
                   style="width: 100%;" @click="openPreviewImage(item.image)"/>

            <!-- 下面选择框-->
            <label class="flex-end gap-20 text-32" @click="onSelectPaper(item, index)" hover-class="hover"
                   hover-stay-time="0">
              <radio :checked="item.selected" color="#1073FF" style="transform:scale(0.9)"/>
              <view>{{ `${index + 1}/${imageList.length}` }}</view>
              <view>{{ lang.print_this_page }}</view>
            </label>
          </view>
        </view>
      </view>

      <!-- 临时不处理-->
      <!--      <view v-if="previewPage !== printParams.page" class="margin-top-40 color-grey text-32 safe-area-padding"-->
      <!--            style="width: 100%;">-->
      <!--        <view class="center gap-20">-->
      <!--          <u-loading-icon/>-->
      <!--          <view>{{ otherLang.loading }}</view>-->
      <!--        </view>-->
      <!--      </view>-->


      <!-- 返回和打印-->
      <view class="column gap-30 fixed-bottom">

        <u-button shape="circle" @click="onBack" size="large" type="primary" :plain="true" :hairline="true">
          {{ otherLang.back }}
        </u-button>


        <u-button
            shape="circle" :disabled="selectedData.length <= 0" @click="onPrintPay" size="large" :hoverStayTime="0"
            color="#3c9cff">
          {{ otherLang.payAndPrint }}
        </u-button>
      </view>

      <view style="height: 360rpx;"/>
    </view>
    <my_upload_card :upload-progress="uploadProgress" :upload-name="printParams.name" :show="showUpload"/>
  </view>
</template>

<script lang="ts">
import Vue from 'vue'
import NavBar from "@/components/nav-bar/nav-bar.vue";
import Tabs from "@/components/tabs/tabs.vue";
import {mapState} from "vuex";
import {getPrice, myReplace} from "@/utils/utils";
import tips from "@/utils/tips";
import my_upload_card from "@/components/my_upload_card/index.vue";
import {createOrder, getTaskId} from "@/services/order";

interface PreviewImage {
  image: string;
  selected: boolean;
  value: number;
}

export default Vue.extend({
  name: "print_preview",
  components: {my_upload_card, NavBar, Tabs},
  data() {
    return {
      // 上传
      showUpload: false,
      uploadProgress: 0,

      selectedTab: 1,
      totalPrice: 0,

      // 打印机参数
      printParams: {},
      previewPage: 0,

      selectedData: [],
      imageList: [], // 当前 预览的图片
    }
  },
  computed: {
    ...mapState(['printer']),
    ...mapState('printFile', ['previewFileImageList']),
    lang() {
      return this.$t('print_preview')
    },

    getUnitPrice() {
      const {dmColor, dmDuplex, dmPaperSize} = this.printParams;
      const prices = this.getPrices(dmPaperSize === 8 ? 'a3' : 'a4');
      return prices[dmDuplex === 1 ? 'single' : 'double'][dmColor === 2 ? 'color' : 'black'];
    }
  },
  onHide() {
    this.$store.dispatch("printFile/clearInterval")
  },
  destroyed() {
    this.$store.dispatch("printFile/clearInterval")
  },
  onLoad(options: any) {
    const {printParams} = JSON.parse(decodeURIComponent(options.params));
    this.printParams = printParams || {};
    // تۇنجى قېتىم كىرگەندە باھانى ھېسابلاش
    if (this.previewFileImageList?.imageList?.length) {
      this.imageList = this.initializeImageList(this.previewFileImageList.imageList);
      this.selectedData = this.imageList.filter(item => item.selected);
      this.calculatePrice();
    }
  },
  watch: {
    'previewFileImageList.imageList': {
      immediate: true,
      handler(newImages) {
        if (newImages?.length) {
          this.imageList = this.initializeImageList(newImages);
          this.selectedData = this.imageList.filter(item => item.selected);
          this.calculatePrice();
        }
      }
    }
  },
  methods: {
    getPrice,
    myReplace,
    initializeImageList(images: string[]) {
      const {jpPageRange} = this.printParams
      let startPage = 1;
      let endPage = images.length;

      if (jpPageRange) {
        const parts = jpPageRange.split('-');
        startPage = parseInt(parts[0]);
        endPage = parseInt(parts[1]);
      }

      return images.map((item: string, index: number) => {
        const pageNum = index + 1;
        return {
          image: item,
          // بەت نومۇرى دائىرە ئىچىدە بولسا true، بولمىسا false
          selected: pageNum >= startPage && pageNum <= endPage,
          value: pageNum
        };
      });
    },
    // tabs click
    handleTabClick(index: number) {
      this.selectedData = []
      this.selectedTab = index;

      if (index === 0) {
        this.imageList.map((item: any) => {
          item.selected = false
        })
      }
      if (index === 1) {
        this.imageList.map((item: any, ind: number) => {
          item.selected = true
          item.value = ind + 1
          this.selectedData.push(item)
        })
      }
      if (index === 2) {
        this.imageList.map((item: any, ind: number) => {
          if (ind % 2) {
            item.selected = true
            item.value = ind + 1
            this.selectedData.push(item)
          } else {
            item.selected = false
          }
        })
      }
      if (index === 3) {
        this.imageList.map((item: any, ind: number) => {
          if (ind % 2) {
            item.selected = false
          } else {
            item.selected = true
            item.value = ind + 1
            this.selectedData.push(item)
          }
        })
      }
      this.calculatePrice()
    },

    // 获取价格
    getPrices(size: string) {
      const prefix = size.toLowerCase();
      return {
        single: {
          black: parseFloat(this.printer[`${prefix}_black_white_price`]),
          color: parseFloat(this.printer[`${prefix}_color_price`])
        },
        double: {
          black: parseFloat(this.printer[`${prefix}_double_black_white_price`]),
          color: parseFloat(this.printer[`${prefix}_double_color_price`])
        }
      };
    },

    // 计算价格
    calculatePrice() {
      const {selectedData, printParams: {dmCopies: copies, dmDuplex, dmColor, dmPaperSize}} = this;
      let totalPages = selectedData.length;

      // 双面的话，需要判断奇偶
      // if (dmDuplex !== 1) {
      //   totalPages = totalPages % 2 ? totalPages + 1 : totalPages;
      // }

      // ئەمەلىي بېسىش بەت سانى (نۇسخا سانى * بەت سانى)
      const pageNum = totalPages * copies;

      // قەغەز تىپىغا ئاساسەن باھا ئېلىش
      const prices = this.getPrices(dmPaperSize === 8 ? 'a3' : 'a4');

      // باھانى ئېلىش
      const price = prices[dmDuplex !== 1 ? 'double' : 'single'][dmColor === 2 ? 'color' : 'black'];

      // ئاخىرقى باھانى ھېسابلاش
      this.totalPrice = dmDuplex !== 1 ? (pageNum / 2) * price : pageNum * price;
    },

    // 每一个 paper 点击
    onSelectPaper(item: PreviewImage, index: number) {
      item.selected = !item.selected;
      if (item.selected) {
        this.selectedData.push({...item, value: index + 1});
      } else {
        const removeIndex = this.selectedData.findIndex(i => i === item);
        this.selectedData.splice(removeIndex, 1);
      }
      this.calculatePrice()
    },
    // 预览
    openPreviewImage(image: string) {
      uni.previewImage({current: 1, urls: [image]})
    },

    async onPrintPay() {
      let {selectedData, printParams, previewFileImageList: {taskTicket}} = this

      // 获取当前页
      const pageRange = selectedData.map(item => {
        return item.value
      })

      console.log("pageRange -=--=-=", pageRange.length)
      printParams.isPreview = 0
      printParams.page = pageRange.length
      printParams.jpPageRange = pageRange.join(',')
      printParams.taskTicket = taskTicket // 传参可以缩短本次打印任务的时间


      console.log("params -=-=-=-==", printParams)
      uni.showLoading({title: '加载中...'});
      const result = await createOrder({
        printer_id: this.printer.id, params: printParams, type: 'file', files: [printParams.jobFile]
      });

      if (result.code === 200) {
        const {wechat_order, order_id} = result.data;
        uni.requestPayment({
          ...wechat_order,
          success: async (res: any) => {
            console.log("uni.requestPayment", res)
            tips.toast('支付成功');
            const tackIdRes = await getTaskId(order_id);
            const {code, data: {task_id}, msg} = tackIdRes;
            if (code === 200) {
              console.log("printFileFun-=--=-=-=- task_id", order_id, task_id)

              printParams.taskId = task_id
              await uni.navigateTo({
                url: `/pages/print_loading/print_loading?params=${
                    encodeURIComponent(JSON.stringify({order_id, type: 0, print_params: printParams}))}`
              });
            } else {
              tips.toast(msg);
              console.log("printFileFun-=--=-=-=-", tackIdRes)
            }
          },
          fail: (err: any) => {
            console.log('fail:', err);
          },
          complete: () => {
            uni.hideLoading();
          }
        });
      } else {
        uni.hideLoading();
        tips.toast(result.msg);
      }
    },

    // 返回
    onBack() {
      const {title, content, confirmText, cancelText} = this.lang.showModal
      uni.showModal({
        title,
        content,
        cancelText,
        confirmText,
        cancelColor: '#999',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
  }
})
</script>

<style scoped>
.content-paper {
  border: 2px solid #E7E8E9;
}

.selected {
  border: 2px solid #03a9f496;
  box-shadow: -1px 2px 20px 3px rgba(74, 152, 213, 0.32);
}

.fixed-bottom {
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(env(safe-area-inset-bottom) + 40rpx);
}


.copies-row {
  padding: 20rpx 0;
  border-top: 2rpx solid #eee;
}

.total-row {
  padding-top: 20rpx;
  border-top: 2rpx solid #eee;
}
</style>